import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 创建一个具有一些线性关系的二分类示例数据
X, y = make_classification(n_samples=100, n_features=4, n_informative=2, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

# 使用K近邻算法进行拟合
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)

# 使用逻辑回归进行拟合
lr = LogisticRegression()
lr.fit(X_train, y_train)

# 绘制数据点和决策边界
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01), np.arange(y_min, y_max, 0.01))
Z_knn = knn.predict(np.c_[xx.ravel(), yy.ravel(), np.zeros_like(xx.ravel()), np.zeros_like(xx.ravel())]).reshape(xx.shape)
Z_lr = lr.predict(np.c_[xx.ravel(), yy.ravel(), np.zeros_like(xx.ravel()), np.zeros_like(xx.ravel())]).reshape(xx.shape)

plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.contourf(xx, yy, Z_knn, alpha=0.4)
plt.scatter(X[:, 0], X[:, 1], c=y, s=20, edgecolor='k')
plt.title("K Nearest Neighbors")
plt.subplot(1, 2, 2)
plt.contourf(xx, yy, Z_lr, alpha=0.4)
plt.scatter(X[:, 0], X[:, 1], c=y, s=20, edgecolor='k')
plt.title("Logistic Regression")
plt.show()

# 输出模型的准确率
print("K Nearest Neighbors Accuracy:", accuracy_score(y_test, knn.predict(X_test)))
print("Logistic Regression Accuracy:", accuracy_score(y_test, lr.predict(X_test)))